/**
 * 
 */
package cn.com.yinhex.util;

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 
 * Created on 2006-12-15
 * 
 * @author WZXIE
 * 
 */

/**
 * @author yw
 * 
 */
public class XMLRow
{

	public Row row = new Row();

	String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>";

	public static String rootElementName = "row";

	public static String xmlHead = "<?xml version=\"1.0\" encoding=\"GBK\"?>";

	/**
	 * 
	 */
	public XMLRow()
	{
		// TODO 自动生成构造函数存根
	}

	public XMLRow(String xml)
	{
		super();
		this.setXml(xml);
		this.XMLtoRow();
	}

	public XMLRow(Row row)
	{
		super();
		this.setRow(row);
		this.RowtoXML();
	}

	public Row getRow()
	{
		return row;
	}

	public void setRow(Row row)
	{
		this.row = row;
	}

	public String getXml()
	{
		return xml;
	}

	public void setXml(String xml)
	{
		this.xml = xml;
	}

	/**
	 * 把单层XML文件转成row表示
	 * 
	 * @param XML
	 * @return
	 */
	public void XMLtoRow()
	{
		// Row row = new Row();
		if (xml == null || xml.length() == 0)
			return;
		try
		{
			Document document = DocumentHelper.parseText(xml);
			Element rootElement = document.getRootElement();
			Iterator elementIterator = rootElement.elementIterator();
			while (elementIterator.hasNext())
			{
				Element nodeElement = (Element) elementIterator.next();
				row.put(nodeElement.getName(), nodeElement.getText());
			}
		} catch (Exception e)
		{
			e.printStackTrace();
			System.out.println("xml:"+xml);
		}
		return;
	}

	/**
	 * 
	 */
	public void RowtoXML()
	{
		if (row == null || row.length() == 0)
			return;
		try
		{
			StringBuffer xmlb = new StringBuffer();
			xmlb.append(xmlHead);
			xmlb.append("<");
			xmlb.append(rootElementName);
			xmlb.append(">");
			for (int i = 0; i < row.length(); i++)
			{
				Object key = row.getKey(i);
				xmlb.append("<");
				xmlb.append(key);
				xmlb.append("><![CDATA[");
				xmlb.append(row.gets(key, ""));
				xmlb.append("]]></");
				xmlb.append(key);
				xmlb.append(">");
			}
			xmlb.append("</");
			xmlb.append(rootElementName);
			xmlb.append(">");
			xml = xmlb.toString();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>";
		xml += "<row><name>jbyw</name><nname>lqt</nname></row>";
		XMLRow xmlRow = new XMLRow(xml);
		Row row = xmlRow.row;
		row.dump();

	}

}
